#include "NotificationDialog.h"
#include <QDebug>
#include <QCheckBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QDateTime>

// Constructor
NotificationDialog::NotificationDialog(const QString& username, QWidget *parent)
    : QDialog(parent), ui(new Ui::viewNotification), m_username(username)
{
    ui->setupUi(this);
    setWindowTitle("通知中心");

    // Initialize the model and table view
    setupModel();

    // Initialize type combo box
    initTypeComboBox();

    // Initial load of notifications
    refreshNotifications();
}

// Destructor
NotificationDialog::~NotificationDialog()
{
    delete ui;
    delete m_model;
}

// Set up the table model
void NotificationDialog::setupModel()
{
    m_model = new QStandardItemModel(this);

    // Set column headers
    QStringList headers;
    headers << "ID" << "选择" << "类型" << "发件人" << "内容" << "已读" << "时间";
    m_model->setHorizontalHeaderLabels(headers);

    // Set model to table view
    ui->notificationTableView->setModel(m_model);

    // Configure table view
    ui->notificationTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->notificationTableView->setSelectionMode(QAbstractItemView::MultiSelection);
    ui->notificationTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->notificationTableView->verticalHeader()->setVisible(false);

    // Hide the ID column
    ui->notificationTableView->setColumnHidden(0, true);

    // Set column widths
    ui->notificationTableView->setColumnWidth(1, 40);  // 选择
    ui->notificationTableView->setColumnWidth(2, 80);  // 类型
    ui->notificationTableView->setColumnWidth(3, 80);  // 发件人
    ui->notificationTableView->setColumnWidth(4, 200); // 内容
    ui->notificationTableView->setColumnWidth(5, 40);  // 已读
    ui->notificationTableView->setColumnWidth(6, 120); // 时间
}

// Initialize notification type combo box
void NotificationDialog::initTypeComboBox()
{
    // Add "全部" as default option
    ui->TypecomboBox->addItem("全部");

    // Get notification types from database
    QSqlQuery query("SELECT DISTINCT type FROM notifications");

    if (query.exec()) {
        while (query.next()) {
            QString type = query.value(0).toString();
            QString displayName = getNotificationTypeDisplayName(type);
            ui->TypecomboBox->addItem(displayName, type);
        }
    } else {
        qDebug() << "获取通知类型失败:" << query.lastError().text();
    }
}

// Get display name for notification type
QString NotificationDialog::getNotificationTypeDisplayName(const QString& type)
{
    if (type == "announcement") {
        return "系统公告";
    } else if (type == "package_status") {
        return "包裹状态";
    } else if (type == "coupon") {
        return "优惠券";
    } else {
        return "未知";
    }
}

// Refresh the notifications list
void NotificationDialog::refreshNotifications()
{
    if (m_username.isEmpty()) {
        QMessageBox::warning(this, "错误", "用户名无效");
        return;
    }

    // Clear the current model
    m_model->removeRows(0, m_model->rowCount());

    // Build the query
    QString queryStr = "SELECT id, sender, type, content, is_read, created_at FROM notifications WHERE receiver = :username";

    // Add filter for type if selected
    QString selectedType;
    int typeIndex = ui->TypecomboBox->currentIndex();

    if (typeIndex > 0) {  // Not "全部"
        selectedType = ui->TypecomboBox->currentData().toString();
        queryStr += " AND type = :type";
    }

    // Add order by
    queryStr += " ORDER BY created_at DESC";

    // Prepare and execute query
    QSqlQuery query;
    query.prepare(queryStr);
    query.bindValue(":username", m_username);

    if (!selectedType.isEmpty()) {
        query.bindValue(":type", selectedType);
    }

    if (!query.exec()) {
        qDebug() << "获取通知失败:" << query.lastError().text();
        return;
    }

    // Check if we should filter for unread only
    bool onlyUnread = (ui->IfReadComboBox->currentIndex() == 0); // 0 = 未读

    // Process query results
    while (query.next()) {
        int id = query.value(0).toInt();
        QString sender = query.value(1).toString();
        QString type = query.value(2).toString();
        QString content = query.value(3).toString();
        bool isRead = query.value(4).toBool();
        QString time = query.value(5).toString();

        // Skip read notifications if only showing unread
        if (onlyUnread && isRead) {
            continue;
        }

        // Create row items
        QList<QStandardItem*> rowItems;

        // ID (hidden)
        QStandardItem* idItem = new QStandardItem(QString::number(id));
        rowItems.append(idItem);

        // Checkbox for selection
        QStandardItem* checkboxItem = new QStandardItem();
        checkboxItem->setCheckable(true);
        checkboxItem->setCheckState(Qt::Unchecked);
        rowItems.append(checkboxItem);

        // Type
        QString typeDisplay = getNotificationTypeDisplayName(type);
        rowItems.append(new QStandardItem(typeDisplay));

        // Sender
        rowItems.append(new QStandardItem(sender));

        // Content
        rowItems.append(new QStandardItem(content));

        // Read status
        QString readStatus = isRead ? "已读" : "未读";
        rowItems.append(new QStandardItem(readStatus));

        // Time
        rowItems.append(new QStandardItem(time));

        // Add row to model
        m_model->appendRow(rowItems);
    }

    // Resize columns to content
    ui->notificationTableView->resizeColumnsToContents();
    ui->notificationTableView->setColumnWidth(4, 200); // Force content column to be wider
}

// Mark notification as read in database
bool NotificationDialog::markNotificationAsRead(int notificationId)
{
    QSqlQuery query;
    query.prepare("UPDATE notifications SET is_read = 1 WHERE id = :id");
    query.bindValue(":id", notificationId);

    if (!query.exec()) {
        qDebug() << "标记通知为已读失败:" << query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

// Delete notification from database
bool NotificationDialog::deleteNotification(int notificationId)
{
    QSqlQuery query;
    query.prepare("DELETE FROM notifications WHERE id = :id");
    query.bindValue(":id", notificationId);

    if (!query.exec()) {
        qDebug() << "删除通知失败:" << query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

// Handle "Mark as Read" button click
void NotificationDialog::on_MarkAsReadBtn_clicked()
{
    QList<int> notificationIds;
    bool anySelected = false;

    // Check for selected notifications
    for (int i = 0; i < m_model->rowCount(); i++) {
        QStandardItem* checkItem = m_model->item(i, 1);
        if (checkItem->checkState() == Qt::Checked) {
            anySelected = true;
            QStandardItem* idItem = m_model->item(i, 0);
            notificationIds.append(idItem->text().toInt());
        }
    }

    if (!anySelected) {
        QMessageBox::information(this, "提示", "请先选择通知");
        return;
    }

    // Mark selected notifications as read
    int successCount = 0;
    for (int id : notificationIds) {
        if (markNotificationAsRead(id)) {
            successCount++;
        }
    }

    // Show result
    if (successCount > 0) {
        QMessageBox::information(this, "成功", QString("成功将 %1 条通知标记为已读").arg(successCount));
        refreshNotifications();
    } else {
        QMessageBox::warning(this, "错误", "标记通知失败");
    }
}

// Handle "Delete" button click
void NotificationDialog::on_DeleteBtn_clicked()
{
    QList<int> notificationIds;
    bool anySelected = false;

    // Check for selected notifications
    for (int i = 0; i < m_model->rowCount(); i++) {
        QStandardItem* checkItem = m_model->item(i, 1);
        if (checkItem->checkState() == Qt::Checked) {
            anySelected = true;
            QStandardItem* idItem = m_model->item(i, 0);
            notificationIds.append(idItem->text().toInt());
        }
    }

    if (!anySelected) {
        QMessageBox::information(this, "提示", "请先选择通知");
        return;
    }

    // Confirm deletion
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, "确认删除", QString("确认删除选中的 %1 条通知？").arg(notificationIds.size()),
        QMessageBox::Yes | QMessageBox::No
        );

    if (reply != QMessageBox::Yes) {
        return;
    }

    // Delete selected notifications
    int successCount = 0;
    for (int id : notificationIds) {
        if (deleteNotification(id)) {
            successCount++;
        }
    }

    // Show result
    if (successCount > 0) {
        QMessageBox::information(this, "成功", QString("成功删除 %1 条通知").arg(successCount));
        refreshNotifications();
    } else {
        QMessageBox::warning(this, "错误", "删除通知失败");
    }
}

// Handle type filter change
void NotificationDialog::on_TypecomboBox_currentIndexChanged(int index)
{
    refreshNotifications();
}

// Handle read status filter change
void NotificationDialog::on_IfReadComboBox_currentIndexChanged(int index)
{
    refreshNotifications();
}
